import React from 'react';
import {WeaErrorPage, WeaTools, WeaTable, WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import loadJs from 'loadjs'
import { openLinkUrl } from '../../util/common';
import jQuery from "jquery";
//建模查询中心元素
class FmcsTable extends React.Component {
	constructor(props){
		super(props);
		//this.imageCarousel = this.imageCarousel.bind(this);
        const staticVersion = `?v${WeaTools && WeaTools.ls && WeaTools.ls.getStr("staticVersion") || 0}`;
		loadJs([`/social/js/drageasy/drageasy.js${staticVersion}`, `/social/js/bootstrap/js/bootstrap.js${staticVersion}`,`/social/im/js/IMUtil_wev8.js${staticVersion}`, `/social/js/imcarousel/imcarousel.js${staticVersion}`]);

	}
	addRowKey(list){
		try{
			list = list.map((item,index)=>{
				item = {
					rowKey:item.key+'_'+index,
					...item
				};
				if(item['sublist']&&item['sublist'].length){
					item['sublist'] = this.addRowKey(item['sublist']);
				}
				return item;
			});
		}catch (e) {
			
		}
		return list;
	}
	render() {
		let { eid, data, esetting, isshowtitle,currentTab } = this.props;
		if (data.isRight == false) {
			return <div style={{height:'40px',lineHeight:'40px',textAlign:'center'}}>{data.data}</div>
		}
		const { tabsetting = {},childrenColumnName='',treeList=[] } = data;
		let list = data.data || [];
		const { widths = [], titles } = tabsetting;
		esetting['widths'] = widths;
		esetting['titles'] = titles;
		let showHeader = true;
		var index = 0;
		for (var k in list[0]) {
			index += 1;
		}
		if (index === 1) {
			showHeader = false;
		}
		let html;
		if(childrenColumnName == '1'){
			list = this.addRowKey(list);
			html =  <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@xoqf60`} key={currentTab} rowKey='rowKey' indentSize="0px" showHeader={isshowtitle == '1' ? true : false}  columns={treeList} pagination={false} dataSource={list} childrenColumnName="sublist" className="cube-list-table"/> ;
		}else{
			html =  <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@8ykdga`} showHeader={isshowtitle == '1' ? true : false}  columns={this.getColumns()} pagination={false} dataSource={list} size="small" /> ;
		}
		return <div className="formmodesearch">{html}</div>;
	}

	componentDidUpdate() {
		this.updateAutoWrap();
	}
	componentDidMount() {
		window['cubeshowDdImg'] = (fieldids,w,h,isbatch,isdownload,docs,formmode_authorizeUrl)=>{
						this.playImg(window.event,fieldids,isdownload,formmode_authorizeUrl);
		}
		this.updateAutoWrap();
	}
	playImg = (e,fieldid,isdownload,formmode_authorizeUrl) => {     // 图片轮播
    const jq = this.getCurrentJQuery();
    const currentWindow = this.getCurrentWindow();
    const imgPool = [];
    let indexNum = 0;
    const fieldids = fieldid.split(',');
    fieldids.map(item=>{
        imgPool.push(`${"/weaver/weaver.file.FileDownload?fileid="+item+formmode_authorizeUrl}`);
    })
    for (let i = 0; i < imgPool.length; i++) {
        if (jq(e.target).attr('data-imgsrc') === imgPool[i]) {
            break;
        } else {
            indexNum++;
        }
    }
    window.IMCarousel.showImgScanner4Pool(true, imgPool, indexNum, null, currentWindow.top);
}

getCurrentJQuery = () => {
	const currentWindow = this.getCurrentWindow();
	return currentWindow.$ || currentWindow.jQuery;
}
// 获取 window
getCurrentWindow = () => {
	const WindowFunc = WeaTools.WindowFunc;
	return WindowFunc.getParent() !== window ? WindowFunc.getTop()
	: window;
}

	updateAutoWrap = ()=>{
		const {isPageAutoWrap}=this.props;
		//需要某个td不受配置控制，则将对应column的className设为customWrap
		let $td = jQuery(
		  " table td:not(.wea-table-operates, .customWrap, .customWrap *)",
		  ReactDOM.findDOMNode(this)
		);
		if (isPageAutoWrap=="0") {
		  $td
			.find('font')
		  	.css('white-space','nowrap')
		  	.css('word-break','keep-all');
		  $td
		  	.find(">div")
			.removeClass("autoWrap")
			.addClass("noWrap");
		  $td
			.find("a")
			.removeClass("autoWrap")
			.addClass("noWrap");
		  $td.removeClass("autoWrap").addClass("noWrap");
		  $td.find("a").map((i, a) => {
			a.title = a.innerText;
		  });
		  $td.find(".wea-url").map((i, d) => {
			d.title = d.innerText;
		  });
		} else {
		  $td
			.find('font')
		  	.css('white-space','normal')
		  	.css('word-break','normal');
		  $td
			.find(">div")
			.removeClass("noWrap")
			.addClass("autoWrap");
		  $td
			.find("a")
			.removeClass("noWrap")
			.addClass("autoWrap");
		  $td.removeClass("noWrap").addClass("autoWrap");
		}

		/**展示树形数据时，每层缩进后 内容左对齐“展开符号” */
		const domArray = jQuery("span[class*='ant-table-row-indent indent-level-']")
		_.forEach(domArray, (item,index)=>{
			const paddingLeft = item.className.split('indent-level-')[1]*20;
			paddingLeft>0 && jQuery(item).parent().css('padding-left',paddingLeft);
		});
	}

	getColumns = ()=>{
		let { data,esetting } = this.props;
		const { imgSymbol, linkmode, widths, titles, ebaseid,  fontStyle = {} } = esetting;
		const { contentfontsize = '12' } = fontStyle;
		const columns = new Array;
		const { tabsetting = {} } = data;
		const { alignmentList={} } = tabsetting;
		const { classname=[] } = alignmentList;
        for (let i = 0; i < alignmentList.length; i++) {
            classname[i] = alignmentList[i] == 'column-text-right' ? 'right' : alignmentList[i] == 'column-text-center' ? 'center' : 'left';
            // console.log(classname[i]);	//获取对齐方式
        }
		//加载行小图标
		if (imgSymbol) {
			const iObj = {
				dataIndex: 'imgSymbol',
				key: 'imgSymbol',
				width: ebaseid=='FormModeCustomSearch'?  '1%': '8px',
				render: () => <img style={{marginBottom:'4px'}} name='esymbol' src={imgSymbol}/>
			}
			columns.push(iObj);
		}
		if(!titles){return []}
		for (let i=0;i<titles.length;i++) {
			var colObj = new Object;
			colObj = {
				dataIndex: 'value'+i,
				key: 'value'+i,
				render: (text, record, index) => {
					if(text && typeof text === 'object' && text.constructor === Array){//链接字段
						return <div style={{ textAlign:classname[i] }}>{this.loadListName(contentfontsize, text, linkmode)}</div>
					}else{//普通文本
						if(typeof text === 'string'){
							if (this.isHtml(text)) {   //判断字符串是否含有html
								return <font style={{display:'block', textAlign:classname[i]}} className={text.indexOf("class='font'") == -1 ? `font wea-f${contentfontsize}` : `wea-f${contentfontsize}`} dangerouslySetInnerHTML={{__html:text}}></font>
							} else {
								return <font style={{display:'block', textAlign:classname[i]}} className={`font wea-f${contentfontsize}`}>{text}</font>
							}
						}else{
							if (this.isHtml(text)) {   //判断字符串是否含有html  
								return <font style={{display:'block', textAlign:classname[i]}} className={text.indexOf("class='font'") == -1 ? `font wea-f${contentfontsize}` : `wea-f${contentfontsize}`} dangerouslySetInnerHTML={{__html:text}}></font>
							} else {
								return <font style={{display:'block', textAlign:classname[i]}} className={`font wea-f${contentfontsize}`}></font>
							}
						}
					}
				}
			}
			if (titles) colObj['title'] = <font className={`font wea-f${contentfontsize}`}  style={{textAlign:classname[i],width:'100%',display:'inline-block'}}>{titles[i]}</font>
			// if (titles) colObj['title'] = titles[i];
			let width = colObj.dataIndex && widths[colObj.dataIndex];
			if(widths[colObj.dataIndex] != '' && widths[colObj.dataIndex] != '*'){
				if(width && width.indexOf('%') == -1){
					width += 'px';
				}
			}
			if (widths) colObj['width'] = width;
			columns.push(colObj);
		}
		return columns;
	}

	//处理属性为集合的数据
	 loadListName = (contentfontsize, list, linkmode) => {
		if (!list || list.length === 0) return <span></span>
		let html = list.map((obj, o) => {
			var dotstr = o === 0 ? "" : " , ";
			if (obj && typeof obj === 'object' && obj.constructor === Object) {
				if (obj.userid) {
					var ahtml = "<a href='javascript:openhrm("+ obj.userid +");' onclick='pointerXY(event)' title="+obj.name+"><font style='color:#000000;' class='font wea-f"+contentfontsize+"'>" + dotstr + obj.name+"</font></a>";
					return <span dangerouslySetInnerHTML={{__html:ahtml}}></span>
				}
				if(obj.namespan != undefined){	
					var shtml = obj.namespan;
					return <font>{dotstr}<a href="javascript:void(0);" onClick={(e) => this.openLinkUrl(obj.link, linkmode, e)} title={obj.name}><font className={`font wea-f${contentfontsize}`}>{obj.name}<span  dangerouslySetInnerHTML={{__html:shtml}}></span></font></a></font>
				}else if(obj.showmethodspan != undefined){
					var shtml = obj.showmethodspan;
					return <div>{dotstr}<a href="javascript:void(0);" onClick={(e) => this.openLinkUrl(obj.link, linkmode, e)} title={obj.name}><div className={`font wea-f${contentfontsize}`} dangerouslySetInnerHTML={{__html:shtml}}></div></a></div>
				}else {
					return <font>{dotstr}<a href="javascript:void(0);" onClick={(e) => this.openLinkUrl(obj.link, linkmode, e)} title={obj.name}><font className={`font wea-f${contentfontsize}`}>{obj.name}</font></a></font>
				}
			} else if (obj && typeof obj === 'object' && obj.constructor === Array) {
				let shtml = obj.map((obj, s) => {
					if (obj.userid) {
						var ahtml = "<a href='javascript:openhrm("+ obj.userid +");' onclick='pointerXY(event)' title="+obj.name+"><font style='color:#000000;' class='font wea-f"+contentfontsize+"'>"+ dotstr + obj.name+"</font></a>";
						return <span dangerouslySetInnerHTML={{__html:ahtml}}></span>
					}
					if (obj.showmethodspan != undefined) {  
						var showhtml = obj.showmethodspan;
						return <a href="javascript:void(0);" onClick={(e) => this.openLinkUrl(obj.link, linkmode,  e)} title={obj.name}><div className={`font wea-f${contentfontsize}`} dangerouslySetInnerHTML={{__html:showhtml}}></div></a>
					} else {
						return <a href="javascript:void(0);" onClick={(e) => this.openLinkUrl(obj.link, linkmode,  e)} title={obj.name}><font className={`font wea-f${contentfontsize}`}>{obj.name}</font></a>
					}
					
				});
				return <font>{dotstr}{shtml}</font>;
			}
		});
		let flag=<span></span>
		if(list[0].img){
			let isnotread=list[0].img.indexOf('/images/ecology8/statusicon/BDNew_wev8.png')>=0;
			if(isnotread){//已读未读标识
				flag=<span style={{verticalAlign:'top',marginLeft:3}}><img class='status' src={list[0].img} title={list[0].desc} complete="complete"/></span>
			}else{
				flag=<span style={{verticalAlign:'top',marginLeft:3}}><img src={list[0].img} title={list[0].desc} complete="complete"/></span>
			}
		}
		return <span className="td-span-formmodecustomsearch">{html}{flag}</span>
	}

	isHtml = (htmlStr) => {
		if(!htmlStr) return false;
		var reg = /<[^>]+>/g;
		return reg.test(htmlStr) || htmlStr.indexOf("&")>-1;
	}

	openLinkUrl = (link,linkmode,e) =>{
		openLinkUrl(link, linkmode,  e)
		this.hideStatusIcon(e);
	}

	hideStatusIcon = (e)=>{
		jQuery(e.currentTarget).closest("tr").find('td .status').hide()
	}

}


class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return (
			<WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@288q1o`} msg={hasErrorMsg?this.props.error:getLabel(385218,"对不起，该页面异常，请联系管理员！")} />
		);
	}
}
FmcsTable = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(FmcsTable);
export default FmcsTable;
